package org.esgi.ppa.HUI;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.DropMode;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import org.esgi.ppa.controller.TestManager;


public class MainWindow extends JFrame {
	private static final long serialVersionUID = -7026081344713443860L;
	public JButton add_test;
	public JTable registeredTests;
	private ControlButtonForMainWindow cbURL;
	public TestManager manager = new TestManager();
	public JButton bRun;
	public JButton bSave;
	public JMenuBar menuBar;
	public JMenu menu;
	public JMenuItem miOpen;

	public MainWindow() {
        initAttribut();
        creeAccueil();
        setTitle("Projet JAVA - Tests Unitaires");
        setDefaultLookAndFeelDecorated(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle bounds = env.getMaximumWindowBounds();
        setBounds(bounds);
        setVisible(true);        
    }

    private void initAttribut(){
    	add_test = new JButton("Ajouter un test unitaire");
    	add_test.setPreferredSize(new Dimension(125,30));
    	cbURL = new ControlButtonForMainWindow(this);
        add_test.addActionListener(cbURL);
        
        // Table and his render
        registeredTests = new JTable(manager);
        XTableRenderer rend = new XTableRenderer(); 
        for(int i=0; i<registeredTests.getColumnModel().getColumnCount(); i++)
        	registeredTests.getColumnModel().getColumn(i).setCellRenderer(rend); 
        registeredTests.setRowSelectionAllowed(true);
        registeredTests.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // On met en place le D&D sur la JTable
        registeredTests.setDropMode(DropMode.INSERT_ROWS);
        registeredTests.setDragEnabled(true);
        registeredTests.setTransferHandler(new MyTransfertHandler());        
        registeredTests.setFillsViewportHeight(true);
        
        bRun = new JButton(new ImageIcon("images/run.png"));
        bRun.addActionListener(cbURL);
        
        bSave = new JButton(new ImageIcon("images/save.png"));
        bSave.addActionListener(cbURL);
        
        menuBar = new JMenuBar();
        menu = new JMenu("Fichier");
        miOpen = new JMenuItem("Ouvrir");
        miOpen.addActionListener(cbURL);
    }

    private void creeAccueil(){
    	menuBar.add(menu);
    	menu.add(miOpen);
    	this.setJMenuBar(menuBar);
    	
    	JPanel eastPan = new JPanel();
    	eastPan.setLayout(new BoxLayout(eastPan, BoxLayout.Y_AXIS));
    	eastPan.add(add_test);
    	getContentPane().add(new JScrollPane(registeredTests), BorderLayout.WEST);
    	getContentPane().add(eastPan, BorderLayout.CENTER);

    	TableColumn column = registeredTests.getColumnModel().getColumn(0);
        column.setMaxWidth(50);
        column = registeredTests.getColumnModel().getColumn(1);
        column.setMaxWidth(600);
        column = registeredTests.getColumnModel().getColumn(2);
        column.setMaxWidth(70);
        column = registeredTests.getColumnModel().getColumn(3);
        column.setMaxWidth(70);
        column = registeredTests.getColumnModel().getColumn(4);
        column.setMaxWidth(70);
        
    	JPanel bottomPan = new JPanel();    	
    	bottomPan.setLayout(new BoxLayout(bottomPan, BoxLayout.X_AXIS));
    	bottomPan.setAlignmentX(RIGHT_ALIGNMENT);
    		
    	bottomPan.add(bSave);
    	bottomPan.add(bRun);
    	getContentPane().add(bottomPan, BorderLayout.SOUTH);
    }
    
    public void displayFen(String msg, JFrame f) {
        try{
            JOptionPane.showMessageDialog(f,
                msg,
                "Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
        catch(HeadlessException y){
            System.out.println(y);
        }
        catch(Exception e){
            System.out.println(e);
        }
    }

    public void showAddTestWindow(){
    	@SuppressWarnings("unused")
		UnitTestingWindow utw = new UnitTestingWindow(this);
    }
    
    void addNewTestToRegisteredTestsPan(Component component){
    	registeredTests.add(component);
    	validate();
    }
    
    TestManager getManager(){
    	return manager;
    }
}


// Set alignement for columns
class XTableRenderer extends DefaultTableCellRenderer { 
	private static final long serialVersionUID = 5146245813570593087L;

	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 
		super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
		this.setHorizontalAlignment(JLabel.CENTER); 
		return this; 
	} 
}

class MyTransfertHandler extends TransferHandler{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
    public int getSourceActions(JComponent c) {
        return TransferHandler.MOVE;
    }
	
    @Override
    protected Transferable createTransferable(JComponent c) {
        JTable t = (JTable) c;
        StringSelection s = new StringSelection(String.valueOf(t.getSelectedRow()));
        return s;
    }
    
    public boolean canImport(TransferHandler.TransferSupport info) {
        if (!info.isDrop()) {
            return false;
        }

        // On ne supporte que les chaines en entr�e
        if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            return false;
        }

        // On recherche l'emplacement du drop
        JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();

        // On ne supporte que les emplacements de drop valides 
        return dl.getDropPoint() != null;
    }

    public boolean importData(TransferHandler.TransferSupport info) {
        if (!canImport(info)) return false;
        
        // On r�cup�re l'emplacement du Drop
        JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation();

        // On r�cup�re la ligne de destinatop du drop
        int dstRow = dl.getRow();            

        // on r�cup�re l'objet de transfert
        Transferable trans = info.getTransferable();

        // On r�cup�re la donn�e utile depuis l'objet de transfert (l'emplacement d'origine de la ligne � bouger)
        int srcRow;
        try {
            srcRow = Integer.parseInt((String)trans.getTransferData(DataFlavor.stringFlavor));                
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }            
        

        // on effectue les modifications sur la JTable
       JTable table = (JTable) info.getComponent();
       TestManager m = (TestManager) table.getModel();
       
       if (dstRow < 0) {
            dstRow = 0;
        }
       if (dstRow > m.getRowCount()-1) {
            dstRow = m.getRowCount()-1;
        }
       
       m.moveRow(srcRow, dstRow);           
       return true;
    }
}
